var gulp = require('gulp');
//编译sass
var sass = require('gulp-sass');
//建立轻量级server
var browserSync = require('browser-sync');
//拼接文件内容
var useref = require('gulp-useref');
//压缩js
var uglify = require('gulp-uglify');
//打印日志
var gutil = require('gulp-util');
//判断文件类型
var gulpIf = require('gulp-if');
//压缩css
var minifyCSS = require('gulp-minify-css');

// 压缩图片，并使用cache 减少重复压缩
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');

// 清理生成文件
var del = require('del');

// 顺序执行任务
var runSequence = require('run-sequence');



gulp.task('clean', function() {
  return del('dist');
});

gulp.task('images', function(){
	return gulp.src('app/images/**/*.+(png|jpg|gif|svg)').pipe(cache(imagemin({
		interlaced: true
	}))).pipe(gulp.dest('dist/images'));
} );

gulp.task('useref', function(){

  return gulp.src('app/*.html')
    // 合并文件，配合 <!-- build --> <!-- emdbuild -->
    .pipe(useref())
    // Minifies only if it's a CSS file
    .pipe(gulpIf('*.css', minifyCSS()))
    // Uglifies only if it's a Javascript file
    .pipe(gulpIf('*.js', uglify()))
    
    .pipe(gulp.dest('dist'))
});

gulp.task('sass',function(){
	console.log('Hello --------------- sass!');
	return gulp.src('app/scss/**/*.scss').pipe(sass())
	.pipe(gulp.dest('app/css'))
	.pipe(browserSync.reload({
		stream: true
	}));
});


gulp.task('browser', function(){
	console.log('Hello --------------- browser!');
	return browserSync({
		server:{
			baseDir: 'app'
		}
	});
});

gulp.task('watch', function() {
	console.log('Hello --------------- watch!');
	gulp.watch(['app/scss/**/*.scss'], gulp.series('sass'));
	gulp.watch('app/*.html', browserSync.reload);
} );

gulp.task('run', gulp.series( 'sass',gulp.parallel('browser','watch'), function(){
	console.log('sass ---- brower -----doWatch!');
}) );

// gulp.task('build', function () {
//   runSequence('clean',
//     gulp.series('sass', 'useref', 'images'), function(){}
//   );
// });

gulp.task('build', gulp.series('clean', 'sass', gulp.parallel('useref','images'), function(){
	console.log('sass ---- brower -----doWatch!');
	return;
}) );